using AzrngTools.Models.Analysis;
using AzrngTools.Utils.Events;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace AzrngTools.ViewModels.Format;

/// <summary>
/// 简单正则解析
/// </summary>
public partial class RegexAnalysisViewModel : ViewModelBase
{
    private readonly IMessageService _messageService;

    public RegexAnalysisViewModel(IMessageService messageService)
    {
        _messageService = messageService;
        RegexWhereText =
            "[\\w]+\\.[\\w]+\\s+[not in|in|]+\\(\\s*'?.+'?,'?.+'?\\s*\\)|(?<=\\(?)[\\w]+\\.[\\w]+[!=|=|not like|like|<>|!~|!]+[\\(\\s]*'.+?'|[\\w]+\\.[\\w]+\\sis not null(?=[)|\\s|;])";

        // OriginSqlText = "select visit_id from visit.visit_record v where v.patient_id='716' and v.visit_id='1111'";
    }

    /// <summary>
    /// 原始内容
    /// </summary>
    [ObservableProperty]
    private string _originSqlText;

    /// <summary>
    /// 正则文本
    /// </summary>
    [ObservableProperty]
    private string _regexWhereText;

    /// <summary>
    /// 处理的文本内容
    /// </summary>
    [ObservableProperty]
    private string _handleWhereContent;

    /// <summary>
    /// where条件处理
    /// </summary>
    [RelayCommand]
    private void WhereHandle()
    {
        try
        {
            if (OriginSqlText.IsNullOrWhiteSpace())
            {
                _messageService.SendMessage("原始SQL不能为空");
                return;
            }

            if (RegexWhereText.IsNullOrWhiteSpace())
            {
                _messageService.SendMessage("正则配置不能为空");
                return;
            }

            var traceSource = new RegexAnalysisSql(OriginSqlText, RegexWhereText);

            // 正则服务解析
            var tableInfos = traceSource.GetTableDetailsInfo();

            var str = JsonSerializer.Serialize(tableInfos, new JsonSerializerOptions
                                                           {
                                                               //整齐打印
                                                               WriteIndented = true,

                                                               //重新编码，解决中文乱码问题
                                                               Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                                                               TypeInfoResolver = AnalysisSqlCacheConfigContext.Default
                                                           });
            HandleWhereContent = str;
        }
        catch (Exception ex)
        {
            _messageService.SendMessage(ex.Message);
        }
    }
}